package com.strelitzia.controller;

import com.mysql.cj.util.StringUtils;
import com.strelitzia.constant.EmailConstant;
import com.strelitzia.email.EmailService;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.utils.RandomValidateCodeUtil;
import com.strelitzia.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @create 2023/12/14 11:32
 */
@RequestMapping("/code")
@RestController
@Slf4j
public class CodeController {
    @Autowired
    private EmailService emailService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @param email 邮箱
     */
   @GetMapping("/{email}")
    public ResultVo sendmail(@PathVariable String email) {
       ResultVo resultVo = new ResultVo();
       // 邮箱格式的正则表达式
       String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
       if(!StringUtils.isNullOrEmpty(email) && Pattern.compile(regex).matcher(email).matches()){
           //生成一个5位随机数
           String code = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
           //调用邮件服务发送邮件
           try {
               emailService.sendMail(email,
                       EmailConstant.EMAIL_SUBJECT, code);
               resultVo.setMsg("发送验证码成功");
           } catch (StrelitziaException e) {
               resultVo.setCode(1);
               resultVo.setMsg(e.getMessage());
           }
       }else {
           resultVo.setCode(1);
           resultVo.setMsg("请输入正确的邮箱");
       }
       return resultVo;
    }


    @GetMapping()
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandomCode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            log.error("获取验证码失败", e);
        }
    }

    @GetMapping("/check/{email}/{code}")
    public ResultVo checkEmailCode(@PathVariable String email,@PathVariable String code) {
        String rCode = redisTemplate.opsForValue().get(email);
        ResultVo resultVo = new ResultVo();
        if (rCode != null && rCode.equals(code)) {
            resultVo.setMsg("验证成功");
        }else {
            resultVo.setCode(1);
            resultVo.setMsg("验证码错误");
        }
        return resultVo;
    }
}
